import React, { useState, useEffect } from 'react';
import { NavBar, Button, Tabs, Modal, Toast, Avatar, Space } from 'antd-mobile';
import { useNavigate, useParams } from 'react-router-dom';
import styles from './UserProfile.module.css';

function UserProfile() {
  const navigate = useNavigate();
  const { userId } = useParams();
  const [userInfo, setUserInfo] = useState(null);
  const [userPosts, setUserPosts] = useState([]);
  const [loading, setLoading] = useState(true);
  const [isFollowing, setIsFollowing] = useState(false);
  const [showMessageModal, setShowMessageModal] = useState(false);
  const [messageContent, setMessageContent] = useState('');

  // 模拟用户数据
  const mockUsers = {
    1: {
      id: 1,
      name: '西瓜',
      avatar: '/33.png',
      bio: '2022级 | 武汉大学 | 视觉传达设计',
      school: '武汉大学',
      major: '视觉传达设计',
      grade: '2022级',
      followers: 230,
      following: 169,
      posts: 12,
      joinDate: '2022-09-01',
      tags: ['设计', '艺术', '毕业', '青春'],
      isVerified: true
    },
    2: {
      id: 2,
      name: '图书馆女孩',
      avatar: '/dt.jpg',
      bio: '文学院学生，喜欢阅读和写作，梦想成为一名作家',
      school: '武汉大学',
      major: '汉语言文学',
      grade: '2021级',
      followers: 234,
      following: 67,
      posts: 45,
      joinDate: '2021-09-01',
      tags: ['阅读', '写作', '文学', '咖啡'],
      isVerified: false
    },
    3: {
      id: 3,
      name: '樱花少女',
      avatar: '/xt.png',
      bio: '艺术设计专业，热爱绘画和设计，喜欢记录校园美景',
      school: '武汉大学',
      major: '艺术设计',
      grade: '2023级',
      followers: 312,
      following: 145,
      posts: 67,
      joinDate: '2023-09-01',
      tags: ['绘画', '设计', '摄影', '旅行'],
      isVerified: true
    },
    4: {
      id: 4,
      name: '学霸小王',
      avatar: '/dt.jpg',
      bio: '数学与统计学院学生，学习成绩优异，乐于助人',
      school: '武汉大学',
      major: '数学与应用数学',
      grade: '2022级',
      followers: 89,
      following: 34,
      posts: 12,
      joinDate: '2022-09-01',
      tags: ['数学', '学习', '运动', '志愿服务'],
      isVerified: false
    }
  };

  // 模拟用户动态数据
  const mockUserPosts = {
    1: [
      {
        id: 1,
        content: '纵然心里有千万般不舍，都也知道真的只能陪到这了，祝各位前程似锦～',
        images: ['/dt.jpg', '/xt.png'],
        time: '2022-05-20 10:00',
        likes: 20,
        comments: 3,
        shares: 3
      },
      {
        id: 2,
        content: '祝各位前程似锦！',
        images: [],
        time: '2022-05-20 10:00',
        likes: 15,
        comments: 2,
        shares: 1
      }
    ],
    2: [
      {
        id: 201,
        content: '今天在图书馆发现了一本很棒的小说，推荐给大家～《百年孤独》真的值得一读！',
        images: [],
        time: '1小时前',
        likes: 89,
        comments: 12,
        shares: 8
      }
    ],
    3: [
      {
        id: 301,
        content: '春天来了！樱花大道上的樱花开始绽放了，虽然还不是最盛的时候，但已经很美了。期待樱花节的到来～',
        images: [],
        time: '3小时前',
        likes: 256,
        comments: 45,
        shares: 32
      }
    ],
    4: [
      {
        id: 401,
        content: '刚刚完成了期末考试，感觉发挥还不错。这学期的课程安排很充实，学到了很多新知识。现在可以好好放松一下了！',
        images: [],
        time: '5小时前',
        likes: 67,
        comments: 8,
        shares: 3
      }
    ]
  };

  useEffect(() => {
    // 模拟加载用户信息
    const loadUserInfo = async () => {
      setLoading(true);
      try {
        // 模拟API调用延迟
        await new Promise(resolve => setTimeout(resolve, 1000));

        const user = mockUsers[userId];
        const posts = mockUserPosts[userId] || [];

        if (user) {
          setUserInfo(user);
          setUserPosts(posts);
          // 模拟关注状态
          setIsFollowing(Math.random() > 0.5);
        } else {
          Toast.show('用户不存在');
          navigate(-1);
        }
      } catch (error) {
        Toast.show('加载用户信息失败');
        navigate(-1);
      } finally {
        setLoading(false);
      }
    };

    if (userId) {
      loadUserInfo();
    }
  }, [userId, navigate]);

  // 处理关注/取消关注
  const handleFollow = () => {
    setIsFollowing(!isFollowing);
    Toast.show({
      content: isFollowing ? '已取消关注' : '关注成功',
      position: 'center'
    });
  };

  // 处理私信
  const handleMessage = () => {
    setShowMessageModal(true);
  };

  // 发送私信
  const sendMessage = () => {
    if (!messageContent.trim()) {
      Toast.show('请输入消息内容');
      return;
    }

    Toast.show({
      content: '消息发送成功',
      position: 'center'
    });
    setShowMessageModal(false);
    setMessageContent('');
  };

  // 处理动态互动
  const handleLike = (postId) => {
    Toast.show({
      content: '点赞成功！',
      position: 'center',
    });
  };

  const handleComment = (postId) => {
    Toast.show({
      content: '评论功能开发中...',
      position: 'center',
    });
  };

  const handleShare = (postId) => {
    Toast.show({
      content: '分享成功！',
      position: 'center',
    });
  };

  if (loading) {
    return (
      <div className={styles.container}>
        <NavBar onBack={() => navigate(-1)} className={styles.navBar}>
          用户详情
        </NavBar>
        <div className={styles.loadingContainer}>
          <div className={styles.loading}>加载中...</div>
        </div>
      </div>
    );
  }

  if (!userInfo) {
    return (
      <div className={styles.container}>
        <NavBar onBack={() => navigate(-1)} className={styles.navBar}>
          用户详情
        </NavBar>
        <div className={styles.errorContainer}>
          <div className={styles.errorText}>用户不存在</div>
        </div>
      </div>
    );
  }

  return (
    <div className={styles.container}>
      <NavBar onBack={() => navigate(-1)} className={styles.navBar}>
        用户详情
      </NavBar>

      <div className={styles.content}>
        {/* 用户基本信息 */}
        <div className={styles.userHeader}>
          <div className={styles.avatarSection}>
            <Avatar src={userInfo.avatar} size={80} className={styles.avatar} />
            {userInfo.isVerified && (
              <div className={styles.verifiedBadge}>✓</div>
            )}
          </div>

          <div className={styles.userBasicInfo}>
            <div className={styles.userName}>
              {userInfo.name}
              {userInfo.isVerified && <span className={styles.verifiedIcon}>✓</span>}
            </div>
            <div className={styles.userSchool}>{userInfo.school}</div>
            <div className={styles.userMajor}>{userInfo.major} · {userInfo.grade}</div>
          </div>

          <div className={styles.actionButtons}>
            <Button
              color={isFollowing ? 'default' : 'primary'}
              size='small'
              onClick={handleFollow}
              className={styles.followButton}
            >
              {isFollowing ? '已关注' : '关注'}
            </Button>
            <Button
              color='primary'
              fill='outline'
              size='small'
              onClick={handleMessage}
              className={styles.messageButton}
            >
              私信
            </Button>
          </div>
        </div>

        {/* 用户统计信息 */}
        <div className={styles.statsSection}>
          <div className={styles.statItem}>
            <div className={styles.statNumber}>{userInfo.posts}</div>
            <div className={styles.statLabel}>动态</div>
          </div>
          <div className={styles.statItem}>
            <div className={styles.statNumber}>{userInfo.followers}</div>
            <div className={styles.statLabel}>粉丝</div>
          </div>
          <div className={styles.statItem}>
            <div className={styles.statNumber}>{userInfo.following}</div>
            <div className={styles.statLabel}>关注</div>
          </div>
        </div>

        {/* 用户简介 */}
        <div className={styles.bioSection}>
          <div className={styles.bioText}>{userInfo.bio}</div>
          <div className={styles.tagsContainer}>
            {userInfo.tags.map((tag, index) => (
              <span key={index} className={styles.tag}>#{tag}</span>
            ))}
          </div>
          <div className={styles.joinDate}>加入时间：{userInfo.joinDate}</div>
        </div>

        {/* 用户动态 */}
        <div className={styles.postsSection}>
          <Tabs>
            <Tabs.Tab title={`动态 (${userPosts.length})`} key="posts">
              <div className={styles.postsContainer}>
                {userPosts.length > 0 ? (
                  userPosts.map(post => (
                    <div
                      key={post.id}
                      className={styles.postItem}
                      onClick={() => navigate(`/post-detail/${post.id}`)}
                    >
                      <div className={styles.postContent}>{post.content}</div>
                      {post.images && post.images.length > 0 && (
                        <div className={styles.postImages}>
                          {post.images.map((img, idx) => (
                            <div key={idx} className={styles.postImageContainer}>
                              <img src={img} alt={`post-${idx}`} className={styles.postImage} />
                            </div>
                          ))}
                        </div>
                      )}
                      <div className={styles.postFooter}>
                        <div className={styles.postTime}>{post.time}</div>
                        <div className={styles.postActions}>
                          <div className={styles.actionButton} onClick={() => handleLike(post.id)}>
                            <span className={styles.actionIcon}>❤️</span> {post.likes}
                          </div>
                          <div className={styles.actionButton} onClick={() => handleComment(post.id)}>
                            <span className={styles.actionIcon}>💬</span> {post.comments}
                          </div>
                          <div className={styles.actionButton} onClick={() => handleShare(post.id)}>
                            <span className={styles.actionIcon}>🔄</span> {post.shares}
                          </div>
                        </div>
                      </div>
                    </div>
                  ))
                ) : (
                  <div className={styles.emptyPosts}>
                    <div className={styles.emptyIcon}>📝</div>
                    <div className={styles.emptyText}>暂无动态</div>
                  </div>
                )}
              </div>
            </Tabs.Tab>
          </Tabs>
        </div>
      </div>

      {/* 私信弹窗 */}
      <Modal
        visible={showMessageModal}
        onClose={() => setShowMessageModal(false)}
        title="发送私信"
        actions={[
          {
            key: 'cancel',
            text: '取消',
            onClick: () => setShowMessageModal(false)
          },
          {
            key: 'send',
            text: '发送',
            primary: true,
            onClick: sendMessage
          }
        ]}
      >
        <div className={styles.messageModal}>
          <div className={styles.messageTarget}>
            发送给：{userInfo.name}
          </div>
          <textarea
            className={styles.messageInput}
            placeholder="请输入消息内容..."
            value={messageContent}
            onChange={(e) => setMessageContent(e.target.value)}
            rows={4}
          />
        </div>
      </Modal>
    </div>
  );
}

export default UserProfile;